<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <p>图片加载 每次只加载3个图片 加载玩一个又补一个进行加载</p>

        <script>
            function limitLoad(urls, handler, limit) {
                const sequence = [].concat(urls);
                let promises = [];
                promises = sequence.splice(0, limit).map((url, index) => {
                    return handler(url).then(() => {
                        return index;
                    });
                });
                let p = Promise.race(promises); //1
                for (let i = 0; i < sequence.length; i++) {
                    p=p.then((res) => {
                        console.log(`p.then((res) => `+res);
                        promises[res] = handler(sequence[i]).then(() => {
                            return res;
                        });
                        return Promise.race(promises); //.then().then() 形成链式的
                    });
                }
            }
            const urls = [
                { info: '1.jpg', time: 2000 },
                { info: '2.jpg', time: 3000 },
                { info: '3.jpg', time: 1000 },
                { info: '4.jpg', time: 2000 },
                { info: '5.jpg', time: 1000 },
                { info: '6.jpg', time: 1000 },
                { info: '7.jpg', time: 1000 },
                { info: '8.jpg', time: 1000 },
            ];
            //设置我们要执行的任务
            function loadImg(url) {
                return new Promise((resolve, reject) => {
                    console.log('---- ' + url.info + ' start!');
                    setTimeout(() => {
                        console.log(url.info + ' OK!!!');
                        resolve();
                    }, url.time);
                });
            }
            limitLoad(urls, loadImg, 3);
        </script>
    </body>
</html>
